package zcw.com.lib_leet_code;

import java.util.Arrays;

import zcw.com.lib_leet_code.bean.TreeNode;
import zcw.com.lib_leet_code.util.Util;

/**
 * Created by 朱城委 on 2022/1/17.<br><br>
 *
 * 中等：求根节点到叶节点数字之和
 */
public class Topic129 {

    public static void main(String[] args) {
        Topic129 instance = new Topic129();

        TreeNode root = Util.createTree(Arrays.asList(1, 2, 3));
        System.out.println(instance.sumNumbers(root));

        root = Util.createTree(Arrays.asList(4, 9, 0, 5, 1));
        System.out.println(instance.sumNumbers(root));
    }

    public int sumNumbers(TreeNode root) {
        return helper(root, 0);
    }

    private int helper(TreeNode root, int value) {
        if(root == null) {
            return 0;
        }

        int newValue = value * 10 + root.val;
        if(root.left == null && root.right == null) {
            return newValue;
        }

        int leftValue = helper(root.left, newValue);
        int rightValue = helper(root.right, newValue);

        return leftValue + rightValue;
    }
}
